package com.alibaba.citrus.ots.sales.plan.facade.service.salesplan;

import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.common.model.ImportRequest;
import com.alibaba.citrus.ots.sales.plan.api.salesplan.SalesPlanLineFileService;
import com.alibaba.citrus.ots.sales.plan.api.salesplan.SalesPlanLineWriteService;
import com.alibaba.citrus.ots.sales.plan.api.setting.SalesPlanScItemQueryService;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.BatchQuerySalesPlanRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.BatchQuerySalesPlanScItemRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanDetailExportRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanDetailViewExportRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanImportRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanLineImportRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.response.SalesPlanDetailExportResponse;
import com.alibaba.citrus.ots.sales.plan.dto.api.response.SalesPlanDetailViewExportResponse;
import com.alibaba.citrus.ots.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.citrus.ots.sales.plan.model.enums.SalesPlanModelEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.StatPoolTypeEnum;
import com.alibaba.citrus.ots.sales.plan.repository.PlatformEnhanceRepository;
import com.alibaba.citrus.ots.sales.plan.repository.SalesPlanRepository;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanLineSDO;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanScItemSDO;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.*;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.PlatformEnhanceService;
import com.epoch.app.bcots.service.SalesPlanService;
import com.epoch.app.otsplatformenhance.model.dto.CustomerAddressIndex;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yuhailin
 * @description:
 * @date 2021-11-06 15:19
 */
@Component
public class SalesPlanLineFileServiceImpl implements SalesPlanLineFileService {
    private static final Log log = Log.getLogger(SalesPlanLineFileServiceImpl.class);

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private SalesPlanScItemQueryService salesPlanScItemQueryService;

    @Resource
    private SalesPlanLineWriteService salesPlanLineWriteService;

    @Resource
    private SalesPlanRepository salesPlanRepository;

    @Resource
    private PlatformEnhanceRepository platformEnhanceRepository;

    @Resource
    private PlatformEnhanceService platformEnhanceService;

    @Resource
    private SalesPlanService salesPlanService;

    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;

    private static final Integer PAGE = 1;
    private static final Integer SIZE = 500;

    @Override
    @FacadeInvoker
    public Result<List<SalesPlanLineImportRequest>> salesPlanLineImportHandle(List<SalesPlanLineImportRequest> requestList, SalesPlanImportRequest salesPlanImportRequest) {
        if (CollectionUtils.isEmpty(requestList)) {
            return Result.success(Lists.newArrayList());
        }
        Set<String> scItemSet = Sets.newHashSet();
        Set<String> customerAddressSet = Sets.newHashSet();
        Set<String> customerSet = Sets.newHashSet();
        Set<String> orgSalesOrganizationCodeSet = Sets.newHashSet();
        Set<String> channelCodeSet = Sets.newHashSet();
        Set<String> itemGroupSet = Sets.newHashSet();
        // 校验必传参数
        List<SalesPlanLineImportRequest> checkRequestList = new ArrayList<>();
        for (SalesPlanLineImportRequest salesPlanLineImportRequest : requestList) {
            if (Strings.isBlank(salesPlanLineImportRequest.getPlanId())) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-15-006", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanLineImportRequest.setPlanId(salesPlanLineImportRequest.getPlanId().trim());
            }

            if (!salesPlanLineImportRequest.getPlanId().trim().equals(salesPlanImportRequest.getPlanId())) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-00-15-020", null).getDisplayErrorMessage());
                continue;
            }

            if (Strings.isBlank(salesPlanLineImportRequest.getCustomerCode())) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-005", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanLineImportRequest.setCustomerCode(salesPlanLineImportRequest.getCustomerCode().trim());
            }

            if (Strings.isBlank(salesPlanLineImportRequest.getCustomerAddress())) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-006", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanLineImportRequest.setCustomerAddress(salesPlanLineImportRequest.getCustomerAddress().trim());
            }

            if (Strings.isBlank(salesPlanLineImportRequest.getScItemId())) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-003", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanLineImportRequest.setScItemId(salesPlanLineImportRequest.getScItemId().trim());
            }

            if (Strings.isBlank(salesPlanLineImportRequest.getChannelCode())) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-030", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanLineImportRequest.setChannelCode(salesPlanLineImportRequest.getChannelCode().trim());
            }

            if (Strings.isBlank(salesPlanLineImportRequest.getOrgSalesOrganizationOutCode())) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-029", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanLineImportRequest.setOrgSalesOrganizationOutCode(salesPlanLineImportRequest.getOrgSalesOrganizationOutCode().trim());
            }

            if (Strings.isBlank(salesPlanLineImportRequest.getItemGroup())) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-031", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanLineImportRequest.setItemGroup(salesPlanLineImportRequest.getItemGroup().trim());
            }

            if (null == salesPlanLineImportRequest.getMonthFirstCount()) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-014", null).getDisplayErrorMessage());
                continue;
            }

            if (null == salesPlanLineImportRequest.getMonthMiddleCount()) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-015", null).getDisplayErrorMessage());
                continue;
            }

            if (null == salesPlanLineImportRequest.getMonthLastCount()) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-016", null).getDisplayErrorMessage());
                continue;
            }

            scItemSet.add(salesPlanLineImportRequest.getScItemId());
            customerAddressSet.add(salesPlanLineImportRequest.getCustomerAddress());
            customerSet.add(salesPlanLineImportRequest.getCustomerCode());
            orgSalesOrganizationCodeSet.add(salesPlanLineImportRequest.getOrgSalesOrganizationOutCode());
            channelCodeSet.add(salesPlanLineImportRequest.getChannelCode());
            itemGroupSet.add(salesPlanLineImportRequest.getItemGroup());
            checkRequestList.add(salesPlanLineImportRequest);
        }
        if (CollectionUtils.isEmpty(checkRequestList)) {
            return Result.success(requestList);
        }
        // 销售组织外部编码 置换 内部ID
        Map<String, com.epoch.app.otsplatformenhance.sdo.OrganizationSDO> organizationMapByOutCode = salesPlanOutCommonService.getOrganizationMapByOutCode(orgSalesOrganizationCodeSet);
        if (organizationMapByOutCode == null) {
            log.error("SalesPlanLineFileServiceImpl.salesPlanLineImportHandle.orgSalesOrganizationCodeResult nothingness");
            ImportRequest.setRequestErrorMessage(checkRequestList, ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        // 查询货品
        Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(scItemSet);
        if (scItemMap == null) {
            log.error("SalesPlanLineFileServiceImpl.salesPlanLineImportHandle.scItemResult nothingness");
            ImportRequest.setRequestErrorMessage(checkRequestList, ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        // 查询 客户地址 (五键唯一)
        Set<String> organizationIdList = organizationMapByOutCode.values().stream().map(com.epoch.app.otsplatformenhance.sdo.OrganizationSDO::getId).collect(Collectors.toSet());
        Map<String, CustomerAddressIndex> customerAddressMap = salesPlanOutCommonService.getCustomerAddressByFive(customerAddressSet, customerSet, organizationIdList, channelCodeSet, itemGroupSet);
        if (customerAddressMap == null) {
            log.error("SalesPlanLineFileServiceImpl.salesPlanLineImportHandle.customerAddressResult nothingness");
            ImportRequest.setRequestErrorMessage(checkRequestList, ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }

        // 获取客户地址对应的组织
        List<SalesPlanLineImportRequest> checkSalesPlanScItemRequestList = new ArrayList<>();
        for (SalesPlanLineImportRequest salesPlanLineImportRequest : checkRequestList) {
            com.epoch.app.otsplatformenhance.sdo.OrganizationSDO organization = organizationMapByOutCode.get(salesPlanLineImportRequest.getOrgSalesOrganizationOutCode());
            if (organization == null) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
                continue;
            }
            CustomerAddressIndex customerAddressSDO = customerAddressMap.get(salesPlanLineImportRequest.getCustomerCode() + salesPlanLineImportRequest.getCustomerAddress() + organization.getId() + salesPlanLineImportRequest.getChannelCode() + salesPlanLineImportRequest.getItemGroup());
            if (Objects.isNull(customerAddressSDO)) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
                continue;
            }
            // 权限校验
            if (salesPlanImportRequest.getBizType() == null && StringUtil.isBlank(salesPlanImportRequest.getBizId())) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-034", null).getDisplayErrorMessage());
                continue;
            }
            // 业务单元以上的能查看所有数据(权限控制)
            if (salesPlanImportRequest.getBizType() >= SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
                SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(salesPlanImportRequest.getBizType());
                if (byOrganizationType == null) {
                    salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-035", null).getDisplayErrorMessage());
                    continue;
                }
                boolean isContinue = false;
                switch (byOrganizationType) {
                    case SALESMAN:
                        if (StringUtil.isBlank(customerAddressSDO.getPrincipal())) {
                            salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-028", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getPrincipal().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-033", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case SALES_DEPARTMENT:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgSaleDepartmentCode())) {
                            salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-029", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgSaleDepartmentCode().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case SALES_CHANNEL:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgSaleChannelCode())) {
                            salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-030", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgSaleChannelCode().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case SALES_ORGANIZATION:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgSaleOrganizationCode())) {
                            salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-031", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgSaleOrganizationCode().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case BUSINESS_UNIT:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgBussinessUnitCode())) {
                            salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-032", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgBussinessUnitCode().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    default:
                }
                if (isContinue) {
                    continue;
                }
            }

//            ScItemSDO scItem = scItemMap.get(salesPlanLineImportRequest.getScItemId());
//            if (Objects.isNull(scItem)) {
//                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
//                continue;
//            }
            if (StringUtil.isNotEmpty(customerAddressSDO.getOrgBussinessUnitCode())) {
                salesPlanLineImportRequest.setOrgBusinessUnitCode(customerAddressSDO.getOrgBussinessUnitCode());
            }
            if (StringUtil.isNotEmpty(customerAddressSDO.getOrgSaleOrganizationCode())) {
                salesPlanLineImportRequest.setOrgSaleOrganizationCode(customerAddressSDO.getOrgSaleOrganizationCode());
            }
            if (StringUtil.isNotEmpty(customerAddressSDO.getOrgSaleChannelCode())) {
                salesPlanLineImportRequest.setOrgSaleChannelCode(customerAddressSDO.getOrgSaleChannelCode());
            }
            checkSalesPlanScItemRequestList.add(salesPlanLineImportRequest);
        }

        if (CollectionUtils.isEmpty(checkSalesPlanScItemRequestList)) {
            return Result.success(requestList);
        }

        // 货品范围
        List<String> scItemIdList = scItemMap.values().stream().map(ScItemSDO::getScItemId).distinct().collect(Collectors.toList());
        List<String> orgBusinessUnitCodeList = checkSalesPlanScItemRequestList.stream().map(SalesPlanLineImportRequest::getOrgBusinessUnitCode).distinct().collect(Collectors.toList());
        List<String> orgSaleOrganizationCodeList = checkSalesPlanScItemRequestList.stream().map(SalesPlanLineImportRequest::getOrgSaleOrganizationCode).distinct().collect(Collectors.toList());
        List<String> orgSaleChannelCodeList = checkSalesPlanScItemRequestList.stream().map(SalesPlanLineImportRequest::getOrgSaleChannelCode).distinct().collect(Collectors.toList());

        BatchQuerySalesPlanScItemRequest batchQuerySalesPlanScItemRequest = new BatchQuerySalesPlanScItemRequest();
        batchQuerySalesPlanScItemRequest.setScItemIds(scItemIdList);
        batchQuerySalesPlanScItemRequest.setOrgBusinessUnitCodeList(orgBusinessUnitCodeList);
        batchQuerySalesPlanScItemRequest.setOrgSaleOrganizationCodeList(orgSaleOrganizationCodeList);
        batchQuerySalesPlanScItemRequest.setOrgSaleChannelCodeList(orgSaleChannelCodeList);
        // 启用状态的数据
        batchQuerySalesPlanScItemRequest.setStatus(1);
        Result<List<SalesPlanScItemSDO>> salesPlanScItemResult = salesPlanScItemQueryService.batchQuerySalesPlanScItem(batchQuerySalesPlanScItemRequest);
        if (salesPlanScItemResult == null || !salesPlanScItemResult.isSuccess() || salesPlanScItemResult.getResult() == null || salesPlanScItemResult.getResult().size() == 0) {
            log.error("SalesPlanLineFileServiceImpl.salesPlanLineImportHandle.salesPlanScItemResult nothingness");
            ImportRequest.setRequestErrorMessage(checkSalesPlanScItemRequestList, ErrorMessage.code("OTS-02-001-00-15-005", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        Map<String, SalesPlanScItemSDO> salesPlanScItemMap = salesPlanScItemResult.getResult().stream().collect(Collectors.toMap(x -> x.getOrgBusinessUnitCode() + x.getOrgSalesOrganizationCode() + x.getOrgSalesChannelCode() + x.getScItemId(), a -> a, (a, b) -> a));

        // 校验计划ID是否存在
        Set<String> planIdSet = checkRequestList.stream().map(SalesPlanLineImportRequest::getPlanId).collect(Collectors.toSet());
        BatchQuerySalesPlanRequest batchQuerySalesPlanRequest = new BatchQuerySalesPlanRequest();
        batchQuerySalesPlanRequest.setIds(Lists.newArrayList(planIdSet));
        batchQuerySalesPlanRequest.setModel(SalesPlanModelEnum.PLAN_MODEL.getModel());
        List<SalesPlanSDO> salesPlanSDOList = salesPlanRepository.batchQuerySalesPlan(batchQuerySalesPlanRequest);
        if (salesPlanSDOList == null || salesPlanSDOList.size() == 0) {
            log.error("SalesPlanLineFileServiceImpl.salesPlanLineImportHandle.salesPlanSDOList nothingness");
            ImportRequest.setRequestErrorMessage(checkSalesPlanScItemRequestList, ErrorMessage.code("OTS-02-002-00-16-001", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        Map<Long, SalesPlanSDO> salesPlanSDOMap = salesPlanSDOList.stream().collect(Collectors.toMap(SalesPlanSDO::getId, a -> a, (a, b) -> a));

        // 数据填充
        List<SalesPlanLineSDO> salesPlanLineSDOList = new ArrayList<>();
        Map<String, SalesPlanLineSDO> salesPlanLineSDOMap = new HashMap<>();
        for (SalesPlanLineImportRequest salesPlanLineImportRequest : checkSalesPlanScItemRequestList) {
            com.epoch.app.otsplatformenhance.sdo.OrganizationSDO organization = organizationMapByOutCode.get(salesPlanLineImportRequest.getOrgSalesOrganizationOutCode());
            // 地址
            CustomerAddressIndex customerAddressSDO = customerAddressMap.get(salesPlanLineImportRequest.getCustomerCode() + salesPlanLineImportRequest.getCustomerAddress() + organization.getId() + salesPlanLineImportRequest.getChannelCode() + salesPlanLineImportRequest.getItemGroup());
//            if (Objects.isNull(customerAddressSDO)) {
//                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
//                continue;
//            }
            // 货品
            ScItemSDO scItem = scItemMap.get(salesPlanLineImportRequest.getScItemId());
            if (Objects.isNull(scItem)) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
                continue;
            }
            // 计划货品
            SalesPlanScItemSDO salesPlanScItemSDO = salesPlanScItemMap.get(customerAddressSDO.getOrgBussinessUnitCode() + customerAddressSDO.getOrgSaleOrganizationCode() + customerAddressSDO.getOrgSaleChannelCode() + scItem.getScItemId());
            if (Objects.isNull(salesPlanScItemSDO)) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-15-005", null).getDisplayErrorMessage());
                continue;
            }
            // 计划
            SalesPlanSDO planSDO = salesPlanSDOMap.get(Long.parseLong(salesPlanLineImportRequest.getPlanId()));
            if (Objects.isNull(planSDO)) {
                salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-00-16-001", null).getDisplayErrorMessage());
                continue;
            }

            // 重复数据校验
            if (MapUtils.isNotEmpty(salesPlanLineSDOMap)) {
                SalesPlanLineSDO salesPlanLineSDO = salesPlanLineSDOMap.get(salesPlanLineImportRequest.getPlanId() + salesPlanLineImportRequest.getCustomerCode() + salesPlanLineImportRequest.getCustomerAddress() + salesPlanLineImportRequest.getOrgSalesOrganizationOutCode() + salesPlanLineImportRequest.getChannelCode() + salesPlanLineImportRequest.getItemGroup() + salesPlanLineImportRequest.getScItemId());
                if (Objects.nonNull(salesPlanLineSDO)) {
                    salesPlanLineImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-00-15-019", null).getDisplayErrorMessage());
                    continue;
                }
            }

            SalesPlanLineSDO salesPlanLineSDO = SalesPlanLineSDO.builder().build();
            BeanUtils.copyProperties(salesPlanLineImportRequest, salesPlanLineSDO);
            salesPlanLineSDO.setChannelCode(Optional.ofNullable(customerAddressSDO.getChannelCode()).orElse(null));
            salesPlanLineSDO.setOrgBusinessUnitCode(Optional.ofNullable(customerAddressSDO.getOrgBussinessUnitCode()).orElse(null));
            salesPlanLineSDO.setOrgSalesOrganizationCode(Optional.ofNullable(customerAddressSDO.getOrgSaleOrganizationCode()).orElse(null));
            salesPlanLineSDO.setOrgSalesChannelCode(Optional.ofNullable(customerAddressSDO.getOrgSaleChannelCode()).orElse(null));
            salesPlanLineSDO.setOrgSalesDepartmentCode(Optional.ofNullable(customerAddressSDO.getOrgSaleDepartmentCode()).orElse(null));
            salesPlanLineSDO.setManageEmployeeId(Optional.ofNullable(customerAddressSDO.getPrincipal()).orElse(null));
            salesPlanLineSDO.setCustomerAddressId(Objects.toString(customerAddressSDO.getId(), null));
            salesPlanLineSDO.setScItemId(scItem.getScItemId());
            salesPlanLineSDO.setScItemGroup(Optional.ofNullable(salesPlanScItemSDO.getScItemGroup()).orElse(null));
            salesPlanLineSDO.setScItemLeafCategoryId(Optional.ofNullable(salesPlanScItemSDO.getScItemLeafCategoryId()).orElse(null));
            salesPlanLineSDO.setScItemRootCategoryId(Optional.ofNullable(salesPlanScItemSDO.getScItemRootCategoryId()).orElse(null));
            salesPlanLineSDO.setCostInsuranceFreight(Optional.ofNullable(salesPlanScItemSDO.getCostInsuranceFreight()).orElse(0L));
            salesPlanLineSDO.setBasicUnit(Optional.ofNullable(salesPlanScItemSDO.getBasicUnit()).orElse(null));
            salesPlanLineSDO.setOutboundPrice(Optional.ofNullable(salesPlanScItemSDO.getOutboundPrice()).orElse(0L));
            Integer monthCount = salesPlanLineImportRequest.getMonthFirstCount() + salesPlanLineImportRequest.getMonthMiddleCount() + salesPlanLineImportRequest.getMonthLastCount();
            salesPlanLineSDO.setMonthCount(monthCount);
            salesPlanLineSDO.setIsBalanced(false);
            salesPlanLineSDO.setOuterId(salesPlanLineImportRequest.getScItemId());
            salesPlanLineSDOList.add(salesPlanLineSDO);
            salesPlanLineSDOMap.put(salesPlanLineImportRequest.getPlanId() + salesPlanLineImportRequest.getCustomerCode() + salesPlanLineImportRequest.getCustomerAddress() + salesPlanLineImportRequest.getOrgSalesOrganizationOutCode() + salesPlanLineImportRequest.getChannelCode() + salesPlanLineImportRequest.getItemGroup() + salesPlanLineImportRequest.getScItemId(), salesPlanLineSDO);
        }
        if (CollectionUtils.isEmpty(salesPlanLineSDOList)) {
            return Result.success(requestList);
        }
        salesPlanLineWriteService.batchImportCreateSalesPlanLine(salesPlanLineSDOList);
        return Result.success(requestList);
    }

    /**
     * 月度计划明细导出服务
     *
     * @param exportRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<List<SalesPlanDetailExportResponse>> SalesPlanDetailExportList(SalesPlanDetailExportRequest exportRequest) {
        try {
            PageQuerySalesPlanLineListResponse salesPlanLineListResponse = salesPlanService.pageQuerySalesPlanLineList(PageQuerySalesPlanLineListRequest.builder()
                    .planId(exportRequest.getPlanId())
                    .customerCode(exportRequest.getCustomerCode())
                    .manageEmployeeId(exportRequest.getManageEmployeeId())
                    .scItemId(exportRequest.getScItemId())
                    .scItemLeafCategoryId(exportRequest.getScItemLeafCategoryId())
                    .status(exportRequest.getStatus())
                    .bizId(exportRequest.getBizId())
                    .bizType(exportRequest.getBizType())
                    .contractDifferenceMoneyStamp(exportRequest.getContractDifferenceMoneyStamp())
                    .start(exportRequest.getStart())
                    .limit(exportRequest.getLimit()).build());
            List<SalesPlanDetailExportResponse> responses = new ArrayList<>();
            if (!salesPlanLineListResponse.getSuccess() || salesPlanLineListResponse.getTotal() == 0 || CollectionUtils.isEmpty(salesPlanLineListResponse.getResult())) {
                return Result.success(responses);
            }
            List<SalesPlanDetailExportRequest> request = JSONObject.parseArray(JSONArray.toJSONString(salesPlanLineListResponse.getResult()), SalesPlanDetailExportRequest.class);
            log.info("月度计划明细导出:" + JSONObject.toJSONString(request));
            //批量查询员工信息
            List<String> employeeIds = Lists.newArrayList();
            List<String> organizationIds = Lists.newArrayList();
            request.stream().forEach(x -> {
                employeeIds.add(x.getUpdater().replace("CZ_", ""));
                employeeIds.add(x.getCreator().replace("CZ_", ""));
                employeeIds.add(x.getManageEmployeeId());
                organizationIds.add(x.getOrgSalesChannelCode());
                organizationIds.add(x.getOrgSalesDepartmentCode());
            });
            Map<String, com.epoch.app.bcots.model.dto.EmployeeSDO> employeeMap;
            Map<String, OrganizationSDO> organizationMap;
            Result<List<com.epoch.app.bcots.model.dto.EmployeeSDO>> employeeListResult = baseDataService.baselineGetEmployeeByIdsAll(
                    BaselineGetEmployeeByIdsAllRequest.builder().ids(employeeIds).build());
            List<com.epoch.app.bcots.model.dto.EmployeeSDO> employeeSDOList = employeeListResult.getResult();
//            List<EmployeeSDO> employeeList = platformEnhanceRepository.getEmployeeList(employeeIds.stream().distinct().collect(Collectors.toList()));
            log.info("月度计划明细导出employeeSDOList={}", JSONObject.toJSONString(employeeSDOList));
            if (CollectionUtils.isNotEmpty(employeeSDOList)) {
                employeeMap = employeeSDOList.stream().collect(Collectors.toMap(com.epoch.app.bcots.model.dto.EmployeeSDO::getId, o -> o));
            } else {
                employeeMap = new HashMap<>();
            }
            //批量查询组织信息
            BaselineGetOrganizationByIdsAllResponse organizationResponse = baseDataService.baselineGetOrganizationByIdsAll(BaselineGetOrganizationByIdsAllRequest.builder()
                    .ids(organizationIds.stream().distinct().collect(Collectors.toList())).build());
            if (!organizationResponse.getSuccess() || CollectionUtils.isEmpty(organizationResponse.getResult())) {
                organizationMap = new HashMap<>();
            } else {
                organizationMap = organizationResponse.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, o -> o));
            }
//        Map<String, EmployeeSDO> map = platformEnhanceRepository.getEmployeeList(ids).stream().collect(Collectors.toMap(EmployeeSDO::getId, o -> o));

            request.forEach(req -> {
                SalesPlanDetailExportResponse salesPlanDetail = convertSalesPlanDetailExportResponse(req, employeeMap, organizationMap);
                salesPlanDetail.setEstimateDiscount(exportRequest.getEstimateDiscount() + "%");
                salesPlanDetail.setPlanTime(exportRequest.getPlanTime());
                salesPlanDetail.setOrgBusinessUnitName(exportRequest.getOrgBusinessUnitName());
                //计算次月建议回复量、计划回复率=次月建议回复量/次月计划提报量
                String monthReturnRate = "0%";
                Integer monthCount = req.getMonthCount();
                Integer monthReturnCount = req.getMonthFirstReturnCount() + req.getMonthMiddleReturnCount() + req.getMonthLastReturnCount();
                salesPlanDetail.setMonthReturnCount(monthReturnCount);
                if (monthCount != 0 && monthReturnCount != 0) {
                    monthReturnRate = new DecimalFormat("0.00").format(new BigDecimal(monthReturnCount.toString())
                            .multiply(new BigDecimal("100"))
                            .divide(new BigDecimal(monthCount.toString()), 2, RoundingMode.HALF_UP)) + "%";
                }
                salesPlanDetail.setMonthReturnRate(monthReturnRate);
                //调整提报量
//                Integer monthAdjustTotalCount = req.getMonthFirstAdjustTotalCount() + req.getMonthMiddleAdjustTotalCount() + req.getMonthLastAdjustTotalCount();
//                salesPlanDetail.setAdjustCount(monthAdjustTotalCount);
//                req.setAdjustCount(monthAdjustTotalCount);
                //计算折扣率、折扣价、修改者、创建者、各种金额
                //销售价(单位：分)
                String costInsuranceFreight;
                Double costInsurance = req.getCostInsuranceFreight();
                //到岸价(单位：分)
                Double outboundPrice = req.getOutboundPrice();
                if (costInsurance == null) {
                    costInsurance = new Double("0");
                }
                if (outboundPrice == null) {
                    outboundPrice = new Double("0");
                }
                //判断销售价是否为0，销售价为0时，不用计算直接返回
                if (costInsurance == 0) {
                    salesPlanDetail.setCostInsuranceFreight(costInsurance);
                    salesPlanDetail.setDiscountPrice(costInsurance);
                } else {
                    //销售价(单位：分)
                    costInsuranceFreight = costInsurance.toString();
                    //折扣价(单位：分)
                    String discountPrice = costInsuranceFreight;
                    //先计算折前的金额(单位：元)
                    Double beforeMonthFirstMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstCount());
                    Double beforeMonthFirstTaskMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstTaskCount());
                    Double beforeMonthFirstAdjustMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstAdjustTotalCount());
                    Double beforeMonthMiddleMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleCount());
                    Double beforeMonthMiddleTaskMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleTaskCount());
                    Double beforeMonthMiddleAdjustMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleAdjustTotalCount());
                    Double beforeMonthLastMoney = calculateMoney(costInsuranceFreight, req.getMonthLastCount());
                    Double beforeMonthLastTaskMoney = calculateMoney(costInsuranceFreight, req.getMonthLastTaskCount());
                    Double beforeMonthLastAdjustMoney = calculateMoney(costInsuranceFreight, req.getMonthLastAdjustTotalCount());
                    Double beforeAdjustMoney = calculateMoney(costInsuranceFreight, req.getAdjustCount());
                    //折后的金额
                    Double monthFirstMoney = beforeMonthFirstMoney;
                    Double monthFirstTaskMoney = beforeMonthFirstTaskMoney;
                    Double monthFirstAdjustMoney = beforeMonthFirstAdjustMoney;
                    Double monthMiddleMoney = beforeMonthMiddleMoney;
                    Double monthMiddleTaskMoney = beforeMonthMiddleTaskMoney;
                    Double monthMiddleAdjustMoney = beforeMonthMiddleAdjustMoney;
                    Double monthLastMoney = beforeMonthLastMoney;
                    Double monthLastTaskMoney = beforeMonthLastTaskMoney;
                    Double monthLastAdjustMoney = beforeMonthLastAdjustMoney;
                    Double adjustMoney = beforeAdjustMoney;
                    //折扣率(需要除100)
                    String estimateDiscount = String.valueOf(exportRequest.getEstimateDiscount() == 0 ? 0 : exportRequest.getEstimateDiscount() / 100);
                    //如果折扣率为0，折前和折后的金额一样
                    if (!estimateDiscount.equals("0")) {
                        //计算折扣价，单位：分
                        discountPrice = new BigDecimal(costInsuranceFreight).multiply(new BigDecimal(
                                new BigDecimal("1").subtract(new BigDecimal(estimateDiscount)).toString())).toString();
                        //计算折后的金额
                        monthFirstMoney = calculateMoney(discountPrice, req.getMonthFirstCount());
                        monthFirstTaskMoney = calculateMoney(discountPrice, req.getMonthFirstTaskCount());
                        monthFirstAdjustMoney = calculateMoney(discountPrice, req.getMonthFirstAdjustTotalCount());
                        monthMiddleMoney = calculateMoney(discountPrice, req.getMonthMiddleCount());
                        monthMiddleTaskMoney = calculateMoney(discountPrice, req.getMonthMiddleTaskCount());
                        monthMiddleAdjustMoney = calculateMoney(discountPrice, req.getMonthMiddleAdjustTotalCount());
                        monthLastMoney = calculateMoney(discountPrice, req.getMonthLastCount());
                        monthLastTaskMoney = calculateMoney(discountPrice, req.getMonthLastTaskCount());
                        monthLastAdjustMoney = calculateMoney(discountPrice, req.getMonthLastAdjustTotalCount());
                        adjustMoney = calculateMoney(discountPrice, req.getAdjustCount());
                    }
                    salesPlanDetail.setBeforeMonthFirstMoney(beforeMonthFirstMoney);
                    salesPlanDetail.setMonthFirstMoney(monthFirstMoney);
                    salesPlanDetail.setBeforeMonthFirstTaskMoney(beforeMonthFirstTaskMoney);
                    salesPlanDetail.setMonthFirstTaskMoney(monthFirstTaskMoney);
                    salesPlanDetail.setBeforeMonthFirstAdjustMoney(beforeMonthFirstAdjustMoney);
                    salesPlanDetail.setMonthFirstAdjustMoney(monthFirstAdjustMoney);
                    salesPlanDetail.setBeforeMonthMiddleMoney(beforeMonthMiddleMoney);
                    salesPlanDetail.setMonthMiddleMoney(monthMiddleMoney);
                    salesPlanDetail.setBeforeMonthMiddleTaskMoney(beforeMonthMiddleTaskMoney);
                    salesPlanDetail.setMonthMiddleTaskMoney(monthMiddleTaskMoney);
                    salesPlanDetail.setBeforeMonthMiddleAdjustMoney(beforeMonthMiddleAdjustMoney);
                    salesPlanDetail.setMonthMiddleAdjustMoney(monthMiddleAdjustMoney);
                    salesPlanDetail.setBeforeMonthLastMoney(beforeMonthLastMoney);
                    salesPlanDetail.setMonthLastMoney(monthLastMoney);
                    salesPlanDetail.setBeforeMonthLastTaskMoney(beforeMonthLastTaskMoney);
                    salesPlanDetail.setMonthLastTaskMoney(monthLastTaskMoney);
                    salesPlanDetail.setBeforeMonthLastAdjustMoney(beforeMonthLastAdjustMoney);
                    salesPlanDetail.setMonthLastAdjustMoney(monthLastAdjustMoney);
                    salesPlanDetail.setBeforeAdjustMoney(beforeAdjustMoney);
                    salesPlanDetail.setAdjustMoney(adjustMoney);
                    //计算完毕以后将价格转为元
                    costInsuranceFreight = fenToYuan(costInsurance).toString();
                    discountPrice = fenToYuan(Double.valueOf(discountPrice)).toString();
                    salesPlanDetail.setCostInsuranceFreight(Double.valueOf(costInsuranceFreight));
                    salesPlanDetail.setDiscountPrice(Double.valueOf(discountPrice));
                }
                //计算到岸金额
                if (outboundPrice == 0) {
                    salesPlanDetail.setOutboundPrice(outboundPrice);
                } else {
                    String outboundPriceString = outboundPrice.toString();
                    Double beforeMonthOutboundMoney = calculateMoney(outboundPriceString, req.getMonthCount());
                    Double beforeTaskOutboundMoney = calculateMoney(outboundPriceString, req.getTaskCount());
                    Double beforeAdjustOutboundMoney = calculateMoney(outboundPriceString, req.getAdjustCount());
                    Double beforeMonthFirstOutboundMoney = calculateMoney(outboundPriceString, req.getMonthFirstCount());
                    Double beforeMonthFirstTaskOutboundMoney = calculateMoney(outboundPriceString, req.getMonthFirstTaskCount());
                    Double beforeMonthFirstAdjustOutboundMoney = calculateMoney(outboundPriceString, req.getMonthFirstAdjustTotalCount());
                    Double beforeMonthMiddleOutboundMoney = calculateMoney(outboundPriceString, req.getMonthMiddleCount());
                    Double beforeMonthMiddleTaskOutboundMoney = calculateMoney(outboundPriceString, req.getMonthMiddleTaskCount());
                    Double beforeMonthMiddleAdjustOutboundMoney = calculateMoney(outboundPriceString, req.getMonthMiddleAdjustTotalCount());
                    Double beforeMonthLastOutboundMoney = calculateMoney(outboundPriceString, req.getMonthLastCount());
                    Double beforeMonthLastTaskOutboundMoney = calculateMoney(outboundPriceString, req.getMonthLastTaskCount());
                    Double beforeMonthLastAdjustOutboundMoney = calculateMoney(outboundPriceString, req.getMonthLastAdjustTotalCount());

                    salesPlanDetail.setOutboundPrice(fenToYuan(outboundPrice));
                    salesPlanDetail.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
                    salesPlanDetail.setBeforeTaskOutboundMoney(beforeTaskOutboundMoney);
                    salesPlanDetail.setBeforeAdjustOutboundMoney(beforeAdjustOutboundMoney);
                    salesPlanDetail.setBeforeMonthFirstOutboundMoney(beforeMonthFirstOutboundMoney);
                    salesPlanDetail.setBeforeMonthFirstTaskOutboundMoney(beforeMonthFirstTaskOutboundMoney);
                    salesPlanDetail.setBeforeMonthFirstAdjustOutboundMoney(beforeMonthFirstAdjustOutboundMoney);
                    salesPlanDetail.setBeforeMonthMiddleOutboundMoney(beforeMonthMiddleOutboundMoney);
                    salesPlanDetail.setBeforeMonthMiddleTaskOutboundMoney(beforeMonthMiddleTaskOutboundMoney);
                    salesPlanDetail.setBeforeMonthMiddleAdjustOutboundMoney(beforeMonthMiddleAdjustOutboundMoney);
                    salesPlanDetail.setBeforeMonthLastOutboundMoney(beforeMonthLastOutboundMoney);
                    salesPlanDetail.setBeforeMonthLastTaskOutboundMoney(beforeMonthLastTaskOutboundMoney);
                    salesPlanDetail.setBeforeMonthLastAdjustOutboundMoney(beforeMonthLastAdjustOutboundMoney);
                }
                //金额保留两位小数转换成字符串
                convertMoneyToString(salesPlanDetail);
                responses.add(salesPlanDetail);
            });
            return Result.success(responses);
        } catch (Exception e) {
            log.error("计划明细导出失败", e);
            return Result.fail("OTS-02-006-00-16-007", ErrorMessage.code("OTS-02-006-00-16-007", null).getDisplayErrorMessage());
        }
    }

    @Override
    @FacadeInvoker
    public Result<List<SalesPlanDetailViewExportResponse>> SalesPlanDetailViewExportList(List<SalesPlanDetailViewExportRequest> request) {
        //每个货品的导出内容
        List<SalesPlanDetailViewExportResponse> responses = new ArrayList<>();
        //分组后的导出内容
        List<SalesPlanDetailViewExportResponse> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(request)) {
            return Result.success(responses);
        }
        try {
            log.info("月度计划汇总导出request" + request.size());
            Map<Integer, List<SalesPlanDetailViewExportRequest>> map = request.stream().collect(Collectors.groupingBy(SalesPlanDetailViewExportRequest::getPoolType));
            if (map.size() != 1) {
                log.error("SalesPlanLineFileServiceImpl.SalesPlanDetailViewExportList.poolType not only");
                throw new FacadeException("汇总类型不一致");
            }
            SalesPlanDetailViewExportRequest salesPlanDetailViewExportRequest = request.get(0);
            String planId = salesPlanDetailViewExportRequest.getPlanId();
            Integer poolType = salesPlanDetailViewExportRequest.getPoolType();
            Map<String, com.epoch.app.bcots.model.dto.EmployeeSDO> employeeMap = new HashMap<>();
            Map<String, OrganizationSDO> organizationMap = new HashMap<>();
            if (poolType.equals(StatPoolTypeEnum.CUSTOMER.getPoolType())) {
                //批量查询员工信息
                List<String> employeeIds = Lists.newArrayList();
                List<String> organizationIds = Lists.newArrayList();
                request.stream().forEach(x -> {
                    employeeIds.add(x.getManageEmployeeId());
                    organizationIds.add(x.getOrgSalesChannelCode());
                    organizationIds.add(x.getOrgSalesDepartmentCode());
                });
                Result<List<com.epoch.app.bcots.model.dto.EmployeeSDO>> employeeListResult = baseDataService.baselineGetEmployeeByIdsAll(
                        BaselineGetEmployeeByIdsAllRequest.builder().ids(employeeIds).build());
                List<com.epoch.app.bcots.model.dto.EmployeeSDO> employeeSDOList = employeeListResult.getResult();
//                List<EmployeeSDO> employeeList = platformEnhanceRepository.getEmployeeList(employeeIds.stream().distinct().collect(Collectors.toList()));
                log.info("月度计划汇总导出employeeSDOList={}", JSONObject.toJSONString(employeeSDOList));
                if (employeeListResult.isSuccess() && CollectionUtils.isNotEmpty(employeeSDOList)) {
                    employeeMap = employeeSDOList.stream().collect(Collectors.toMap(com.epoch.app.bcots.model.dto.EmployeeSDO::getId, o -> o));
                }
                //批量查询组织信息
                BaselineGetOrganizationByIdsAllResponse organizationByIdsResponse = baseDataService.baselineGetOrganizationByIdsAll(BaselineGetOrganizationByIdsAllRequest.builder()
                        .ids(organizationIds.stream().distinct().collect(Collectors.toList())).build());
                if (organizationByIdsResponse.getSuccess() && CollectionUtils.isNotEmpty(organizationByIdsResponse.getResult())) {
                    organizationMap = organizationByIdsResponse.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, o -> o));
                }
            }
            log.info("月度计划汇总导出employeeMap={}", JSONObject.toJSONString(employeeMap));
            log.info("月度计划汇总导出organizationMap={}", JSONObject.toJSONString(organizationMap));
            Map<String, com.epoch.app.bcots.model.dto.EmployeeSDO> finalEmployeeMap = employeeMap;
            Map<String, OrganizationSDO> finalOrganizationMap = organizationMap;
            request.forEach(req -> {
                //计算次月建议回复量、计划回复率=次月建议回复量/次月计划提报量
                Integer monthCount = req.getMonthCount();
                Integer monthReturnCount = req.getMonthFirstReturnCount() + req.getMonthMiddleReturnCount() + req.getMonthLastReturnCount();
                //计算次月调整回复量
                Integer monthAdjustReturnCount = req.getMonthFirstAdjustReturnCount() + req.getMonthMiddleAdjustReturnCount() + req.getMonthLastAdjustReturnCount();
                //过滤数量都为0的数据
                Integer adjustCount = req.getAdjustCount();
                Integer taskCount = req.getTaskCount();
                if ((monthCount == null || monthCount == 0) && monthReturnCount == 0 && monthAdjustReturnCount == 0 && (adjustCount == null || adjustCount == 0) && (taskCount == null || taskCount == 0)) {
                    return;
                }

                SalesPlanDetailViewExportResponse salesPlanDetailView = convertSalesPlanDetailViewExportResponse(req, finalEmployeeMap, finalOrganizationMap);
                salesPlanDetailView.setMonthReturnCount(monthReturnCount);
                salesPlanDetailView.setMonthReturnRate(calculatePercent(monthReturnCount.toString(), monthCount.toString()));
                salesPlanDetailView.setMonthAdjustReturnCount(monthAdjustReturnCount);
                //调整提报量
//                Integer monthAdjustTotalCount = req.getMonthFirstAdjustTotalCount() + req.getMonthMiddleAdjustTotalCount() + req.getMonthLastAdjustTotalCount();
//                salesPlanDetailView.setAdjustCount(monthAdjustTotalCount);
//                req.setAdjustCount(monthAdjustTotalCount);

                //计算折扣率、折扣价、修改者、创建者、各种金额
                //销售价(单位：分)
                String costInsuranceFreight;
                Double costInsurance = req.getCostInsuranceFreight();
                if (costInsurance == null) {
                    costInsurance = new Double("0");
                }
                //判断销售价是否为0，销售价为0时，不用计算直接返回
                if (costInsurance == 0) {
                    salesPlanDetailView.setCostInsuranceFreight(costInsurance);
                    salesPlanDetailView.setDiscountPrice(costInsurance);
                } else {
                    //销售价(单位：分)
                    costInsuranceFreight = costInsurance.toString();
                    //折扣价(单位：分)
                    String discountPrice = costInsuranceFreight;
                    //先计算折前的金额(单位：元)
                    Double beforeAdjustReturnMoney = calculateMoney(costInsuranceFreight, monthAdjustReturnCount);
                    Double beforeMonthFirstMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstCount());
                    Double beforeMonthFirstTaskMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstTaskCount());
                    Double beforeMonthFirstAdjustMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstAdjustCount());
                    Double beforeMonthFirstAdjustReturnMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstAdjustReturnCount());
                    Double beforeMonthMiddleMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleCount());
                    Double beforeMonthMiddleTaskMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleTaskCount());
                    Double beforeMonthMiddleAdjustMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleAdjustCount());
                    Double beforeMonthMiddleAdjustReturnMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleAdjustReturnCount());
                    Double beforeMonthLastMoney = calculateMoney(costInsuranceFreight, req.getMonthLastCount());
                    Double beforeMonthLastTaskMoney = calculateMoney(costInsuranceFreight, req.getMonthLastTaskCount());
                    Double beforeMonthLastAdjustMoney = calculateMoney(costInsuranceFreight, req.getMonthLastAdjustCount());
                    Double beforeMonthLastAdjustReturnMoney = calculateMoney(costInsuranceFreight, req.getMonthLastAdjustReturnCount());
                    Double beforeAdjustMoney = calculateMoney(costInsuranceFreight, req.getAdjustCount());
                    //折后的金额
                    Double adjustReturnMoney = beforeAdjustReturnMoney;
                    Double monthFirstMoney = beforeMonthFirstMoney;
                    Double monthFirstTaskMoney = beforeMonthFirstTaskMoney;
                    Double monthFirstAdjustMoney = beforeMonthFirstAdjustMoney;
                    Double monthFirstAdjustReturnMoney = beforeMonthFirstAdjustReturnMoney;
                    Double monthMiddleMoney = beforeMonthMiddleMoney;
                    Double monthMiddleTaskMoney = beforeMonthMiddleTaskMoney;
                    Double monthMiddleAdjustMoney = beforeMonthMiddleAdjustMoney;
                    Double monthMiddleAdjustReturnMoney = beforeMonthMiddleAdjustReturnMoney;
                    Double monthLastMoney = beforeMonthLastMoney;
                    Double monthLastTaskMoney = beforeMonthLastTaskMoney;
                    Double monthLastAdjustMoney = beforeMonthLastAdjustMoney;
                    Double monthLastAdjustReturnMoney = beforeMonthLastAdjustReturnMoney;
                    Double adjustMoney = beforeAdjustMoney;
                    //折扣率(需要除100)
                    String estimateDiscount = String.valueOf(req.getEstimateDiscount() == 0 ? 0 : req.getEstimateDiscount() / 100);
                    //如果折扣率为0，折前和折后的金额一样
                    if (!estimateDiscount.equals("0")) {
                        //计算折扣价，单位：分
                        discountPrice = new BigDecimal(costInsuranceFreight).multiply(new BigDecimal(
                                new BigDecimal("1").subtract(new BigDecimal(estimateDiscount)).toString())).toString();
                        //计算折后的金额
                        adjustReturnMoney = calculateMoney(discountPrice, monthAdjustReturnCount);
                        monthFirstMoney = calculateMoney(discountPrice, req.getMonthFirstCount());
                        monthFirstTaskMoney = calculateMoney(discountPrice, req.getMonthFirstTaskCount());
                        monthFirstAdjustMoney = calculateMoney(discountPrice, req.getMonthFirstAdjustTotalCount());
                        monthFirstAdjustReturnMoney = calculateMoney(discountPrice, req.getMonthFirstAdjustReturnCount());
                        monthMiddleMoney = calculateMoney(discountPrice, req.getMonthMiddleCount());
                        monthMiddleTaskMoney = calculateMoney(discountPrice, req.getMonthMiddleTaskCount());
                        monthMiddleAdjustMoney = calculateMoney(discountPrice, req.getMonthMiddleAdjustTotalCount());
                        monthMiddleAdjustReturnMoney = calculateMoney(discountPrice, req.getMonthMiddleAdjustReturnCount());
                        monthLastMoney = calculateMoney(discountPrice, req.getMonthLastCount());
                        monthLastTaskMoney = calculateMoney(discountPrice, req.getMonthLastTaskCount());
                        monthLastAdjustMoney = calculateMoney(discountPrice, req.getMonthLastAdjustTotalCount());
                        monthLastAdjustReturnMoney = calculateMoney(discountPrice, req.getMonthLastAdjustReturnCount());
                        adjustMoney = calculateMoney(discountPrice, req.getAdjustCount());
                    }
                    salesPlanDetailView.setBeforeAdjustReturnMoney(beforeAdjustReturnMoney);
                    salesPlanDetailView.setAdjustReturnMoney(adjustReturnMoney);
                    salesPlanDetailView.setBeforeMonthFirstMoney(beforeMonthFirstMoney);
                    salesPlanDetailView.setMonthFirstMoney(monthFirstMoney);
                    salesPlanDetailView.setBeforeMonthFirstTaskMoney(beforeMonthFirstTaskMoney);
                    salesPlanDetailView.setMonthFirstTaskMoney(monthFirstTaskMoney);
                    salesPlanDetailView.setBeforeMonthFirstAdjustMoney(beforeMonthFirstAdjustMoney);
                    salesPlanDetailView.setMonthFirstAdjustMoney(monthFirstAdjustMoney);
                    salesPlanDetailView.setBeforeMonthFirstAdjustReturnMoney(beforeMonthFirstAdjustReturnMoney);
                    salesPlanDetailView.setMonthFirstAdjustReturnMoney(monthFirstAdjustReturnMoney);

                    salesPlanDetailView.setBeforeMonthMiddleMoney(beforeMonthMiddleMoney);
                    salesPlanDetailView.setMonthMiddleMoney(monthMiddleMoney);
                    salesPlanDetailView.setBeforeMonthMiddleTaskMoney(beforeMonthMiddleTaskMoney);
                    salesPlanDetailView.setMonthMiddleTaskMoney(monthMiddleTaskMoney);
                    salesPlanDetailView.setBeforeMonthMiddleAdjustMoney(beforeMonthMiddleAdjustMoney);
                    salesPlanDetailView.setMonthMiddleAdjustMoney(monthMiddleAdjustMoney);
                    salesPlanDetailView.setBeforeMonthMiddleAdjustReturnMoney(beforeMonthMiddleAdjustReturnMoney);
                    salesPlanDetailView.setMonthMiddleAdjustReturnMoney(monthMiddleAdjustReturnMoney);

                    salesPlanDetailView.setBeforeMonthLastMoney(beforeMonthLastMoney);
                    salesPlanDetailView.setMonthLastMoney(monthLastMoney);
                    salesPlanDetailView.setBeforeMonthLastTaskMoney(beforeMonthLastTaskMoney);
                    salesPlanDetailView.setMonthLastTaskMoney(monthLastTaskMoney);
                    salesPlanDetailView.setBeforeMonthLastAdjustMoney(beforeMonthLastAdjustMoney);
                    salesPlanDetailView.setMonthLastAdjustMoney(monthLastAdjustMoney);
                    salesPlanDetailView.setBeforeMonthLastAdjustReturnMoney(beforeMonthLastAdjustReturnMoney);
                    salesPlanDetailView.setMonthLastAdjustReturnMoney(monthLastAdjustReturnMoney);

                    salesPlanDetailView.setBeforeAdjustMoney(beforeAdjustMoney);
                    salesPlanDetailView.setAdjustMoney(adjustMoney);
                    //计算完毕以后将价格转为元
                    costInsuranceFreight = fenToYuan(costInsurance).toString();
                    discountPrice = fenToYuan(Double.valueOf(discountPrice)).toString();
                    salesPlanDetailView.setCostInsuranceFreight(Double.valueOf(costInsuranceFreight));
                    salesPlanDetailView.setDiscountPrice(Double.valueOf(discountPrice));
                }
                responses.add(salesPlanDetailView);
            });

            log.info("月度计划汇总导出responses" + responses.size());
            //根据poolType进行分组求和 2：货品维度 3：组织维度 4：类目维度 null：客户维度
            StatPoolTypeEnum poolTypeEnum = StatPoolTypeEnum.getByPoolType(poolType);
            switch (poolTypeEnum) {
                case CUSTOMER:
                    //客户维度根据客户编码和客户地址求和
//                    Map<Optional<String>, List<SalesPlanDetailViewExportResponse>> mapGroupByCustomer = responses.stream().collect(Collectors.groupingBy(o -> Optional.of(o.getCustomerCode() + o.getCustomerAddress())));
                    Map<Optional<String>, List<SalesPlanDetailViewExportResponse>> mapGroupByCustomer = responses.stream().collect(Collectors.groupingBy(o -> Optional.of(o.getCustomerAddressId())));
                    log.info("月度计划汇总导出mapGroupByCustomer" + mapGroupByCustomer.size());
//                    List<String> customerCodeList = request.stream().map(o -> o.getCustomerCode() + o.getCustomerAddress()).distinct().collect(Collectors.toList());
                    List<String> customerAddressIdList = request.stream().map(SalesPlanDetailViewExportRequest::getCustomerAddressId).distinct().collect(Collectors.toList());
                    log.info("月度计划汇总导出customerAddressIdList" + customerAddressIdList.size());
                    sumHandle(result, mapGroupByCustomer, customerAddressIdList, null, null, poolType);
                    //从页面直接获取合同量、合同金额
                    customerGetContract(result, planId, poolType);
                    break;
                case SC_ITEM:
                    //货品维度直接返回
                    //从页面直接获取合同量、合同金额
                    result.addAll(responses);
                    scItemGetContract(result, planId, poolTypeEnum);
                    break;
                case ORGANIZATION:
                    //组织维度根据组织id求和
                    Map<Optional<String>, List<SalesPlanDetailViewExportResponse>> mapGroupByOrganization = responses.stream().collect(Collectors.groupingBy(o -> Optional.ofNullable(o.getBizId())));
                    List<String> bizIdList = request.stream().map(SalesPlanDetailViewExportRequest::getBizId).distinct().collect(Collectors.toList());
                    //查询组织详情
                    Map<String, OrganizationSDO> organizationSDOMap;
                    BaselineGetOrganizationByIds2Request getOrganizationByIds2Request = new BaselineGetOrganizationByIds2Request();
                    getOrganizationByIds2Request.setIds(bizIdList);
                    getOrganizationByIds2Request.setStatus(1);
                    BaselineGetOrganizationByIds2Response organizationResponse = baseDataService.baselineGetOrganizationByIds2(getOrganizationByIds2Request);
                    if (organizationResponse != null && CollectionUtils.isNotEmpty(organizationResponse.getResult())) {
                        organizationSDOMap = organizationResponse.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, o -> o));
                    } else {
                        organizationSDOMap = new HashMap<>();
                    }
                    sumHandle(result, mapGroupByOrganization, bizIdList, organizationSDOMap, null, poolType);
                    //从页面直接获取合同量、合同金额
                    scItemGetContract(result, planId, poolTypeEnum);
                    break;
                case CATEGORY:
                    //类目维度根据类目id求和
                    Map<Optional<String>, List<SalesPlanDetailViewExportResponse>> mapGroupByCategory = responses.stream().collect(Collectors.groupingBy(o -> Optional.ofNullable(o.getScItemCategoryId())));
                    List<String> categoryIdList = request.stream().map(SalesPlanDetailViewExportRequest::getScItemCategoryId).distinct().collect(Collectors.toList());
                    //查询类目详情
                    BatchQueryCategoryInfoRequest categoryInfoRequest = new BatchQueryCategoryInfoRequest();
                    categoryInfoRequest.setCategoryIdList(categoryIdList);
                    Object categoryResponse = platformEnhanceService.batchQueryCategoryInfo(categoryInfoRequest);
                    List<Category> categorySDOList = Lists.newArrayList();
                    if (categoryResponse != null) {
                        JSONObject object = JSONObject.parseObject(JSON.toJSONString(categoryResponse));
                        if (object.getBoolean("success") && object.getJSONObject("result") != null
                                && !org.apache.commons.collections.CollectionUtils.isEmpty(object.getJSONObject("result").getJSONArray("categorySDOList"))) {
                            categorySDOList = object.getJSONObject("result").getJSONArray("categorySDOList").toJavaList(Category.class);
                        }
                    }
                    Map<String, Category> categoryMap = categorySDOList.stream().collect(Collectors.toMap(Category::getCategoryId, o -> o));
                    sumHandle(result, mapGroupByCategory, categoryIdList, null, categoryMap, poolType);
                    //从页面直接获取合同量、合同金额
                    scItemGetContract(result, planId, poolTypeEnum);
                    break;
                default:
            }

        } catch (Exception e) {
            log.error("计划明细汇总视图导出失败", e);
            return Result.fail("OTS-02-006-00-16-004", ErrorMessage.code("OTS-02-006-00-16-004", null).getDisplayErrorMessage());
        }
        log.info("月度计划汇总导出result" + result.size());
        return Result.success(result);
    }

    @Override
    @FacadeInvoker
    public PageQuerySalesPlanLineList2Response getSalesPlanLineList(PageQuerySalesPlanLineList2Request pageQuerySalesPlanLineList2Request) {
        PageQuerySalesPlanLineList2Response response = PageQuerySalesPlanLineList2Response.builder().result(Lists.newArrayList()).build();
        try {
            if (pageQuerySalesPlanLineList2Request == null) {
                return response;
            }
            response = salesPlanService.pageQuerySalesPlanLineList2(pageQuerySalesPlanLineList2Request);
            log.info("getSalesPlanLineList:" + JSONObject.toJSONString(response));
            Integer total = response.getTotal();
            List<SalesPlanLineSDO2> result = response.getResult();
            if (!response.getSuccess() || CollectionUtils.isEmpty(result) || total == 0) {
                return response;
            }
            result = Lists.newArrayList();
            int totalPage = total % 100 == 0 ? total / 100 : total / 100 + 1;
            for (int i = 0; i < totalPage; i++) {
                pageQuerySalesPlanLineList2Request.setStart(i * 100);
                PageQuerySalesPlanLineList2Response listResponse = salesPlanService.pageQuerySalesPlanLineList2(pageQuerySalesPlanLineList2Request);
                if (listResponse.getSuccess() && CollectionUtils.isNotEmpty(listResponse.getResult()) && listResponse.getTotal() != 0) {
                    result.addAll(listResponse.getResult());
                }
            }
            result = result.stream().filter(salesPlanLine -> salesPlanLine.getStatus() == 2).collect(Collectors.toList());
            response.setResult(result);
            log.info("getSalesPlanLineList:" + response.getResult().size());
            return response;
        } catch (Exception e) {
            log.info("月度计划明细汇总导出异常" + JSONObject.toJSONString(e));
            return response;
        }
    }

    private void sumHandle(List<SalesPlanDetailViewExportResponse> result, Map<Optional<String>, List<SalesPlanDetailViewExportResponse>> map, List<String> ids, Map<String, OrganizationSDO> organizationSDOMap, Map<String, Category> categoryMap, Integer poolType) {
        for (String id : ids) {
            List<SalesPlanDetailViewExportResponse> list = map.get(Optional.ofNullable(id));
            if (CollectionUtils.isEmpty(list)) {
                continue;
            }
            SalesPlanDetailViewExportResponse target = list.get(0);
            if (list.size() != 1) {
                mergeSource(target, list, organizationSDOMap, categoryMap, poolType);
            } else {
                convertTarget(target, organizationSDOMap, categoryMap, poolType);
            }
            result.add(target);
        }
    }

    private void mergeSource(SalesPlanDetailViewExportResponse target, List<SalesPlanDetailViewExportResponse> source, Map<String, OrganizationSDO> organizationSDOMap, Map<String, Category> categoryMap, Integer poolType) {
        //求和
//        target.setMonthContractCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthContractCount).sum());
//        target.setBeforeMonthContractMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthContractMoney).sum());
//        target.setMonthContractMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthContractMoney).sum());
        target.setMonthCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthCount).sum());
        target.setMonthReturnCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthReturnCount).sum());
        target.setBeforeMonthMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthMoney).sum());
        target.setMonthMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthMoney).sum());
        target.setTaskCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getTaskCount).sum());
        target.setBeforeTaskMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeTaskMoney).sum());
        target.setTaskMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getTaskMoney).sum());
        target.setAdjustCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getAdjustCount).sum());
        target.setBeforeAdjustMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeAdjustMoney).sum());
        target.setAdjustMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getAdjustMoney).sum());
        target.setMonthAdjustReturnCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthAdjustReturnCount).sum());
        target.setBeforeAdjustReturnMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeAdjustReturnMoney).sum());
        target.setAdjustReturnMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getAdjustReturnMoney).sum());
        target.setMonthFirstCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthFirstCount).sum());
        target.setMonthFirstReturnCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthFirstReturnCount).sum());
        target.setBeforeMonthFirstMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthFirstMoney).sum());
        target.setMonthFirstMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthFirstMoney).sum());
        target.setMonthFirstTaskCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthFirstTaskCount).sum());
        target.setBeforeMonthFirstTaskMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthFirstTaskMoney).sum());
        target.setMonthFirstTaskMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthFirstTaskMoney).sum());
        target.setMonthFirstAdjustCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthFirstAdjustCount).sum());
        target.setBeforeMonthFirstAdjustMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthFirstAdjustMoney).sum());
        target.setMonthFirstAdjustMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthFirstAdjustMoney).sum());
        target.setMonthFirstAdjustReturnCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthFirstAdjustReturnCount).sum());
        target.setBeforeMonthFirstAdjustReturnMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthFirstAdjustReturnMoney).sum());
        target.setMonthFirstAdjustReturnMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthFirstAdjustReturnMoney).sum());
        target.setMonthMiddleCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthMiddleCount).sum());
        target.setMonthMiddleReturnCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthMiddleReturnCount).sum());
        target.setBeforeMonthMiddleMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthMiddleMoney).sum());
        target.setMonthMiddleMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthMiddleMoney).sum());
        target.setMonthMiddleTaskCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthMiddleTaskCount).sum());
        target.setBeforeMonthMiddleTaskMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthMiddleTaskMoney).sum());
        target.setMonthMiddleTaskMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthMiddleTaskMoney).sum());
        target.setMonthMiddleAdjustCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthMiddleAdjustCount).sum());
        target.setBeforeMonthMiddleAdjustMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthMiddleAdjustMoney).sum());
        target.setMonthMiddleAdjustMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthMiddleAdjustMoney).sum());
        target.setMonthMiddleAdjustReturnCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthMiddleAdjustReturnCount).sum());
        target.setBeforeMonthMiddleAdjustReturnMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthMiddleAdjustReturnMoney).sum());
        target.setMonthMiddleAdjustReturnMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthMiddleAdjustReturnMoney).sum());
        target.setMonthLastCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthLastCount).sum());
        target.setMonthLastReturnCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthLastReturnCount).sum());
        target.setBeforeMonthLastMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthLastMoney).sum());
        target.setMonthLastMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthLastMoney).sum());
        target.setMonthLastTaskCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthLastTaskCount).sum());
        target.setBeforeMonthLastTaskMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthLastTaskMoney).sum());
        target.setMonthLastTaskMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthLastTaskMoney).sum());
        target.setMonthLastAdjustCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthLastAdjustCount).sum());
        target.setBeforeMonthLastAdjustMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthLastAdjustMoney).sum());
        target.setMonthLastAdjustMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthLastAdjustMoney).sum());
        target.setMonthLastAdjustReturnCount(source.stream().mapToInt(SalesPlanDetailViewExportResponse::getMonthLastAdjustReturnCount).sum());
        target.setBeforeMonthLastAdjustReturnMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getBeforeMonthLastAdjustReturnMoney).sum());
        target.setMonthLastAdjustReturnMoney(source.stream().mapToDouble(SalesPlanDetailViewExportResponse::getMonthLastAdjustReturnMoney).sum());
        //需要重新计算的
        target.setMonthReturnRate(calculatePercent(target.getMonthReturnCount().toString(), target.getMonthCount().toString()));
//        target.setBeforeContractSatisfaction(calculatePercent(target.getBeforeMonthMoney().toString(), target.getBeforeMonthContractMoney().toString()));
//        target.setContractSatisfaction(calculatePercent(target.getMonthMoney().toString(), target.getMonthContractMoney().toString()));
        convertTarget(target, organizationSDOMap, categoryMap, poolType);
    }

    private void convertTarget(SalesPlanDetailViewExportResponse target, Map<String, OrganizationSDO> organizationSDOMap, Map<String, Category> categoryMap, Integer poolType) {
        //汇总以后不展示的字段
        target.setDiscountPrice(null);
        target.setCostInsuranceFreight(null);
        target.setEstimateDiscount(null);
        //需要手动添加的字段:组织名称、组织编码、类目名称
        if (MapUtils.isNotEmpty(organizationSDOMap)) {
            Optional<OrganizationSDO> organizationSDO = Optional.ofNullable(organizationSDOMap.get(target.getBizId()));
            if (ObjectUtils.isEmpty(organizationSDO)) {
                target.setBizCode("");
                target.setBizName("");
            } else {
                target.setBizCode(Optional.ofNullable(organizationSDOMap.get(target.getBizId()).getOutCode()).orElse(""));
                target.setBizName(Optional.ofNullable(organizationSDOMap.get(target.getBizId()).getName()).orElse(""));
            }
        }
        if (MapUtils.isNotEmpty(categoryMap)) {
            Optional<Category> category = Optional.ofNullable(categoryMap.get(target.getScItemCategoryId()));
            if (ObjectUtils.isEmpty(category)) {
                target.setScItemCategoryName("其他类目");
            } else {
                target.setScItemCategoryName(Optional.ofNullable(categoryMap.get(target.getScItemCategoryId()).getCategoryName()).orElse("其他类目"));
            }
        }
    }

    private SalesPlanDetailViewExportResponse convertSalesPlanDetailViewExportResponse(SalesPlanDetailViewExportRequest req, Map<String, com.epoch.app.bcots.model.dto.EmployeeSDO> employeeMap, Map<String, OrganizationSDO> organizationMap) {
        SalesPlanDetailViewExportResponse salesPlanDetail = new SalesPlanDetailViewExportResponse();
        BeanUtils.copyProperties(req, salesPlanDetail);
        salesPlanDetail.setEstimateDiscount(req.getEstimateDiscount() + "%");
        salesPlanDetail.setBeforeContractSatisfaction(Optional.ofNullable(req.getBeforeContractSatisfaction()).orElse(0d) + "%");
        salesPlanDetail.setContractSatisfaction(Optional.ofNullable(req.getContractSatisfaction()).orElse(0d) + "%");
        //接口返回的金额都是分，需要转成元
        salesPlanDetail.setBeforeMonthContractMoney(fenToYuan(req.getBeforeMonthContractMoney()));
        salesPlanDetail.setMonthContractMoney(fenToYuan(req.getMonthContractMoney()));
        salesPlanDetail.setBeforeMonthMoney(fenToYuan(req.getBeforeMonthMoney()));
        salesPlanDetail.setMonthMoney(fenToYuan(req.getMonthMoney()));
        salesPlanDetail.setBeforeTaskMoney(fenToYuan(req.getBeforeTaskMoney()));
        salesPlanDetail.setTaskMoney(fenToYuan(req.getTaskMoney()));
        salesPlanDetail.setBeforeAdjustMoney(fenToYuan(req.getBeforeAdjustMoney()));
        salesPlanDetail.setAdjustMoney(fenToYuan(req.getAdjustMoney()));

        if (MapUtils.isNotEmpty(employeeMap) && null != employeeMap.get(req.getManageEmployeeId())) {
            salesPlanDetail.setManageEmployeeName(employeeMap.get(req.getManageEmployeeId()).getName());
            salesPlanDetail.setManageEmployeeNick(employeeMap.get(req.getManageEmployeeId()).getNick());
        }
        if (MapUtils.isNotEmpty(organizationMap)) {
            if (null != organizationMap.get(req.getOrgSalesChannelCode())) {
                salesPlanDetail.setOrgSalesChannelName(organizationMap.get(req.getOrgSalesChannelCode()).getName());
            }
            if (null != organizationMap.get(req.getOrgSalesDepartmentCode())) {
                salesPlanDetail.setOrgSalesDepartmentName(organizationMap.get(req.getOrgSalesDepartmentCode()).getName());
            }
        }
        return salesPlanDetail;
    }

    private String calculatePercent(String source1, String source2) {
        if (Double.parseDouble(source1) == 0 || Double.parseDouble(source2) == 0) {
            return "0%";
        }
        return new DecimalFormat("0.00").format(new BigDecimal(source1)
                .multiply(new BigDecimal("100"))
                .divide(new BigDecimal(source2), 2, RoundingMode.HALF_UP)) + "%";
    }

    private Double calculateMoney(String price, Integer count) {
        if (count == 0) {
            return new Double("0");
        }
        String money = new DecimalFormat("0.00").format(new BigDecimal(price)
                .multiply(new BigDecimal(count.toString()))
                .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
        return Double.valueOf(money);
    }

    public Double fenToYuan(Double price) {
        if (price == 0) {
            return price;
        }
        String money = new DecimalFormat("0.00").format(new BigDecimal(price.toString())
                .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
        return Double.valueOf(money);
    }

    private SalesPlanDetailExportResponse convertSalesPlanDetailExportResponse(SalesPlanDetailExportRequest req, Map<String, com.epoch.app.bcots.model.dto.EmployeeSDO> employeeMap, Map<String, OrganizationSDO> organizationMap) {
        SalesPlanDetailExportResponse salesPlanDetail = new SalesPlanDetailExportResponse();
        BeanUtils.copyProperties(req, salesPlanDetail);
        salesPlanDetail.setBeforeContractSatisfaction(Optional.ofNullable(req.getBeforeContractSatisfaction()).orElse(0d) + "%");
        salesPlanDetail.setContractSatisfaction(Optional.ofNullable(req.getContractSatisfaction()).orElse(0d) + "%");
        //接口返回的金额都是分，需要转成元
        salesPlanDetail.setBeforeMonthContractMoney(fenToYuan(req.getBeforeMonthContractMoney()));
        salesPlanDetail.setMonthContractMoney(fenToYuan(req.getMonthContractMoney()));
        salesPlanDetail.setBeforeMonthMoney(fenToYuan(req.getBeforeMonthMoney()));
        salesPlanDetail.setMonthMoney(fenToYuan(req.getMonthMoney()));
        salesPlanDetail.setBeforeTaskMoney(fenToYuan(req.getBeforeTaskMoney()));
        salesPlanDetail.setTaskMoney(fenToYuan(req.getTaskMoney()));
        salesPlanDetail.setBeforeAdjustMoney(fenToYuan(req.getBeforeAdjustMoney()));
        salesPlanDetail.setAdjustMoney(fenToYuan(req.getAdjustMoney()));
        //可能根据id查不到员工
        if (MapUtils.isNotEmpty(employeeMap)) {
            if (null != employeeMap.get(req.getUpdater().replace("CZ_", ""))) {
                salesPlanDetail.setUpdater(employeeMap.get(req.getUpdater().replace("CZ_", "")).getName());
            }
            if (null != employeeMap.get(req.getCreator().replace("CZ_", ""))) {
                salesPlanDetail.setCreator(employeeMap.get(req.getCreator().replace("CZ_", "")).getName());
            }
            if (null != employeeMap.get(req.getManageEmployeeId())) {
                salesPlanDetail.setManageEmployeeName(employeeMap.get(req.getManageEmployeeId()).getName());
                salesPlanDetail.setManageEmployeeNick(employeeMap.get(req.getManageEmployeeId()).getNick());
            }
        }
        if (MapUtils.isNotEmpty(organizationMap)) {
            if (null != organizationMap.get(req.getOrgSalesChannelCode())) {
                salesPlanDetail.setOrgSalesChannelName(organizationMap.get(req.getOrgSalesChannelCode()).getName());
            }
            if (null != organizationMap.get(req.getOrgSalesDepartmentCode())) {
                salesPlanDetail.setOrgSalesDepartmentName(organizationMap.get(req.getOrgSalesDepartmentCode()).getName());
            }
        }
        return salesPlanDetail;
    }

    @Builder
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Category {
        private String categoryId;
        private String categoryName;

    }

    private boolean isJsonObject(String valueAsString) {
        return valueAsString.startsWith("{") && valueAsString.endsWith("}") && valueAsString.contains(":");
    }

    private void convertMoneyToString(SalesPlanDetailExportResponse salesPlanDetail) {
        salesPlanDetail.setCostInsuranceFreightString(keepTwoDecimal(salesPlanDetail.getCostInsuranceFreight()));
        salesPlanDetail.setDiscountPriceString(keepTwoDecimal(salesPlanDetail.getDiscountPrice()));
        salesPlanDetail.setBeforeMonthContractMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthContractMoney()));
        salesPlanDetail.setMonthContractMoneyString(keepTwoDecimal(salesPlanDetail.getMonthContractMoney()));
        salesPlanDetail.setBeforeMonthMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthMoney()));
        salesPlanDetail.setMonthMoneyString(keepTwoDecimal(salesPlanDetail.getMonthMoney()));
        salesPlanDetail.setBeforeTaskMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeTaskMoney()));
        salesPlanDetail.setTaskMoneyString(keepTwoDecimal(salesPlanDetail.getTaskMoney()));
        salesPlanDetail.setBeforeAdjustMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeAdjustMoney()));
        salesPlanDetail.setAdjustMoneyString(keepTwoDecimal(salesPlanDetail.getAdjustMoney()));
        salesPlanDetail.setBeforeMonthFirstMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthFirstMoney()));
        salesPlanDetail.setMonthFirstMoneyString(keepTwoDecimal(salesPlanDetail.getMonthFirstMoney()));
        salesPlanDetail.setBeforeMonthFirstTaskMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthFirstTaskMoney()));
        salesPlanDetail.setMonthFirstTaskMoneyString(keepTwoDecimal(salesPlanDetail.getMonthFirstTaskMoney()));
        salesPlanDetail.setBeforeMonthFirstAdjustMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthFirstAdjustMoney()));
        salesPlanDetail.setMonthFirstAdjustMoneyString(keepTwoDecimal(salesPlanDetail.getMonthFirstAdjustMoney()));
        salesPlanDetail.setBeforeMonthMiddleMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthMiddleMoney()));
        salesPlanDetail.setMonthMiddleMoneyString(keepTwoDecimal(salesPlanDetail.getMonthMiddleMoney()));
        salesPlanDetail.setBeforeMonthMiddleTaskMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthMiddleTaskMoney()));
        salesPlanDetail.setMonthMiddleTaskMoneyString(keepTwoDecimal(salesPlanDetail.getMonthMiddleTaskMoney()));
        salesPlanDetail.setBeforeMonthMiddleAdjustMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthMiddleAdjustMoney()));
        salesPlanDetail.setMonthMiddleAdjustMoneyString(keepTwoDecimal(salesPlanDetail.getMonthMiddleAdjustMoney()));
        salesPlanDetail.setBeforeMonthLastMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthLastMoney()));
        salesPlanDetail.setMonthLastMoneyString(keepTwoDecimal(salesPlanDetail.getMonthLastMoney()));
        salesPlanDetail.setBeforeMonthLastTaskMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthLastTaskMoney()));
        salesPlanDetail.setMonthLastTaskMoneyString(keepTwoDecimal(salesPlanDetail.getMonthLastTaskMoney()));
        salesPlanDetail.setBeforeMonthLastAdjustMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthLastAdjustMoney()));
        salesPlanDetail.setMonthLastAdjustMoneyString(keepTwoDecimal(salesPlanDetail.getMonthLastAdjustMoney()));

        //到岸价
        salesPlanDetail.setOutboundPriceString(keepTwoDecimal(salesPlanDetail.getOutboundPrice()));
        salesPlanDetail.setBeforeMonthOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthOutboundMoney()));
        salesPlanDetail.setBeforeTaskOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeTaskOutboundMoney()));
        salesPlanDetail.setBeforeAdjustOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeAdjustOutboundMoney()));
        salesPlanDetail.setBeforeMonthFirstOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthFirstOutboundMoney()));
        salesPlanDetail.setBeforeMonthFirstTaskOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthFirstTaskOutboundMoney()));
        salesPlanDetail.setBeforeMonthFirstAdjustOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthFirstAdjustOutboundMoney()));
        salesPlanDetail.setBeforeMonthMiddleOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthMiddleOutboundMoney()));
        salesPlanDetail.setBeforeMonthMiddleTaskOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthMiddleTaskOutboundMoney()));
        salesPlanDetail.setBeforeMonthMiddleAdjustOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthMiddleAdjustOutboundMoney()));
        salesPlanDetail.setBeforeMonthLastOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthLastOutboundMoney()));
        salesPlanDetail.setBeforeMonthLastTaskOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthLastTaskOutboundMoney()));
        salesPlanDetail.setBeforeMonthLastAdjustOutboundMoneyString(keepTwoDecimal(salesPlanDetail.getBeforeMonthLastAdjustOutboundMoney()));
    }

    private void convertMoneyToString(SalesPlanDetailViewExportResponse salesPlanDetailView, Integer poolType) {
        if (poolType == 2) {
            salesPlanDetailView.setCostInsuranceFreightString(keepTwoDecimal(salesPlanDetailView.getCostInsuranceFreight()));
            salesPlanDetailView.setDiscountPriceString(keepTwoDecimal(salesPlanDetailView.getDiscountPrice()));
        }
        salesPlanDetailView.setBeforeMonthContractMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthContractMoney()));
        salesPlanDetailView.setMonthContractMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthContractMoney()));

        salesPlanDetailView.setBeforeMonthMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthMoney()));
        salesPlanDetailView.setMonthMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthMoney()));
        salesPlanDetailView.setBeforeTaskMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeTaskMoney()));
        salesPlanDetailView.setTaskMoneyString(keepTwoDecimal(salesPlanDetailView.getTaskMoney()));
        salesPlanDetailView.setBeforeAdjustMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeAdjustMoney()));
        salesPlanDetailView.setAdjustMoneyString(keepTwoDecimal(salesPlanDetailView.getAdjustMoney()));
        salesPlanDetailView.setBeforeAdjustReturnMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeAdjustReturnMoney()));
        salesPlanDetailView.setAdjustReturnMoneyString(keepTwoDecimal(salesPlanDetailView.getAdjustReturnMoney()));

        salesPlanDetailView.setBeforeMonthFirstMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthFirstMoney()));
        salesPlanDetailView.setMonthFirstMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthFirstMoney()));
        salesPlanDetailView.setBeforeMonthFirstTaskMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthFirstTaskMoney()));
        salesPlanDetailView.setMonthFirstTaskMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthFirstTaskMoney()));
        salesPlanDetailView.setBeforeMonthFirstAdjustMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthFirstAdjustMoney()));
        salesPlanDetailView.setMonthFirstAdjustMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthFirstAdjustMoney()));
        salesPlanDetailView.setBeforeMonthFirstAdjustReturnMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthFirstAdjustReturnMoney()));
        salesPlanDetailView.setMonthFirstAdjustReturnMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthFirstAdjustReturnMoney()));

        salesPlanDetailView.setBeforeMonthMiddleMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthMiddleMoney()));
        salesPlanDetailView.setMonthMiddleMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthMiddleMoney()));
        salesPlanDetailView.setBeforeMonthMiddleTaskMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthMiddleTaskMoney()));
        salesPlanDetailView.setMonthMiddleTaskMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthMiddleTaskMoney()));
        salesPlanDetailView.setBeforeMonthMiddleAdjustMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthMiddleAdjustMoney()));
        salesPlanDetailView.setMonthMiddleAdjustMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthMiddleAdjustMoney()));
        salesPlanDetailView.setBeforeMonthMiddleAdjustReturnMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthMiddleAdjustReturnMoney()));
        salesPlanDetailView.setMonthMiddleAdjustReturnMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthMiddleAdjustReturnMoney()));

        salesPlanDetailView.setBeforeMonthLastMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthLastMoney()));
        salesPlanDetailView.setMonthLastMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthLastMoney()));
        salesPlanDetailView.setBeforeMonthLastTaskMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthLastTaskMoney()));
        salesPlanDetailView.setMonthLastTaskMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthLastTaskMoney()));
        salesPlanDetailView.setBeforeMonthLastAdjustMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthLastAdjustMoney()));
        salesPlanDetailView.setMonthLastAdjustMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthLastAdjustMoney()));
        salesPlanDetailView.setBeforeMonthLastAdjustReturnMoneyString(keepTwoDecimal(salesPlanDetailView.getBeforeMonthLastAdjustReturnMoney()));
        salesPlanDetailView.setMonthLastAdjustReturnMoneyString(keepTwoDecimal(salesPlanDetailView.getMonthLastAdjustReturnMoney()));
    }

    //保留两位小数
    private String keepTwoDecimal(Double source) {
        if (source == null || source == 0) {
            return "0.00";
        }
        return new DecimalFormat("0.00").format(new BigDecimal(source.toString()));
    }


    private void scItemGetContract(List<SalesPlanDetailViewExportResponse> result, String planId, StatPoolTypeEnum poolTypeEnum) {
        try {
            List<SalesPlanDetailViewExportResponse> planScItemList = Lists.newArrayList();
            Integer page = PAGE;
            Integer total = SIZE;
            while (page * SIZE <= total) {
                PageQueryPlanScItemListResponse queryResult = salesPlanService.pageQueryPlanScItemList(PageQueryPlanScItemListRequest.builder()
                        .planId(planId).poolType(poolTypeEnum.getPoolType()).page(page).size(SIZE).build());
                if (!queryResult.getSuccess() || CollectionUtils.isEmpty(queryResult.getResult())) {
                    break;
                }
                List<SalesPlanDetailViewExportResponse> list = JSON.parseArray(JSONObject.toJSONString(queryResult.getResult()), SalesPlanDetailViewExportResponse.class);
                planScItemList.addAll(list);
                page += PAGE;
                total = queryResult.getTotal();
            }
            if (CollectionUtils.isEmpty(planScItemList)) {
                log.info("月度计划汇总导出scItemGetContract查询合同数据失败,汇总维度={}", poolTypeEnum.getDesc());
                return;
            }
            Map<String, SalesPlanDetailViewExportResponse> listMap = new HashMap<>();
            if (poolTypeEnum == StatPoolTypeEnum.SC_ITEM) {
                listMap = planScItemList.stream().collect(Collectors.toMap(SalesPlanDetailViewExportResponse::getOuterId, o -> o, (a, b) -> a));
            } else if (poolTypeEnum == StatPoolTypeEnum.ORGANIZATION) {
                listMap = planScItemList.stream().collect(Collectors.toMap(SalesPlanDetailViewExportResponse::getBizId, o -> o, (a, b) -> a));
            } else if (poolTypeEnum == StatPoolTypeEnum.CATEGORY) {
                listMap = planScItemList.stream().collect(Collectors.toMap(SalesPlanDetailViewExportResponse::getScItemCategoryId, o -> o, (a, b) -> a));
            } else {
                return;
            }
            for (SalesPlanDetailViewExportResponse target : result) {
                SalesPlanDetailViewExportResponse planScItemSDO = new SalesPlanDetailViewExportResponse();
                if (poolTypeEnum == StatPoolTypeEnum.SC_ITEM) {
                    planScItemSDO = listMap.get(target.getOuterId());
                } else if (poolTypeEnum == StatPoolTypeEnum.ORGANIZATION) {
                    planScItemSDO = listMap.get(target.getBizId());
                } else {
                    planScItemSDO = listMap.get(target.getScItemCategoryId());
                }
                if (null == planScItemSDO) {
                    continue;
                }
                target.setMonthContractCount(planScItemSDO.getMonthContractCount());
                target.setMonthContractMoney(fenToYuan(planScItemSDO.getMonthContractMoney()));
                target.setBeforeMonthContractMoney(fenToYuan(planScItemSDO.getBeforeMonthContractMoney()));
                target.setContractSatisfaction(planScItemSDO.getContractSatisfaction());
                target.setBeforeContractSatisfaction(planScItemSDO.getBeforeContractSatisfaction());
                convertMoneyToString(target, poolTypeEnum.getPoolType());
            }
        } catch (Exception e) {
            log.info("月度计划汇总导出scItemGetContract获取合同数据失败={}", e);
        }
    }

    private void customerGetContract(List<SalesPlanDetailViewExportResponse> result, String planId, Integer poolType) {
        try {
            List<SalesPlanStatCustomerSDO> planStatCustomerList = Lists.newArrayList();
            Integer page = PAGE;
            Integer total = SIZE;
            while (page * SIZE <= total) {
                PageQueryPlanCustomerListResponse queryResult = salesPlanService.pageQueryPlanCustomerList(PageQueryPlanCustomerListRequest.builder()
                        .planId(planId).page(page).size(SIZE).build());
                if (!queryResult.getSuccess() || CollectionUtils.isEmpty(queryResult.getResult())) {
                    break;
                }
                planStatCustomerList.addAll(queryResult.getResult());
                page += PAGE;
                total = queryResult.getTotal();
            }
            if (CollectionUtils.isEmpty(planStatCustomerList)) {
                log.info("月度计划汇总导出customerGetContract查询合同数据失败");
                return;
            }
            Map</*CustomerAddressId*/String, SalesPlanStatCustomerSDO> listMap = planStatCustomerList.stream().collect(Collectors.toMap(SalesPlanStatCustomerSDO::getCustomerAddressId, o -> o, (a, b) -> a));
            List<SalesPlanDetailViewExportResponse> list = Lists.newArrayList();
            for (SalesPlanDetailViewExportResponse target : result) {
                SalesPlanStatCustomerSDO planCustomerSDO = listMap.get(target.getCustomerAddressId());
                target.setMonthContractCount(planCustomerSDO.getMonthContractCount());
                target.setMonthContractMoney(fenToYuan(planCustomerSDO.getMonthContractMoney().doubleValue()));
                target.setBeforeMonthContractMoney(fenToYuan(planCustomerSDO.getBeforeMonthContractMoney().doubleValue()));
                target.setContractSatisfaction(planCustomerSDO.getContractSatisfaction().toString());
                target.setBeforeContractSatisfaction(planCustomerSDO.getBeforeContractSatisfaction().toString());
                convertMoneyToString(target, poolType);
            }
        } catch (Exception e) {
            log.info("月度计划汇总导出customerGetContract获取合同数据失败={}", e);
        }
    }
}
